import json
import hashlib
import requests
from django.conf import settings
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from demo import models
# 沙箱环境地质：https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
def index(request):
    obj = models.UserInfo.objects.get(id=1)
    return render(request,'demo.html',{'obj':obj})


def bind_qcode(request):
    """
    生成二维码
    :param request: 
    :return: 
    """
    ret = {'code': 1000}
    user = str(models.UserInfo.objects.get(id=1).id)
    try:
        m=hashlib.md5()
        m.update(user.encode('utf-8'))
        access_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo&state={state}#wechat_redirect"
        access_url = access_url.format(
            # 商户的appid
            appid=settings.WECHAT_CONFIG["app_id"], # 'wx6edde7a6a97e4fcd',
            # 回调地址
            redirect_uri=settings.WECHAT_CONFIG["redirect_uri"],
            # 当前登录用户的唯一id
            state=m.hexdigest # 为当前用户生成MD5值
        )
        ret['data'] = access_url
    except Exception as e:
        ret['code'] = 1001
        ret['msg'] = '失败'
        ret['data'] = ''

    return JsonResponse(ret)


def callback(request):
    """
    用户在手机微信上扫码后，微信自动调用该方法。
    用于获取扫码用户的唯一ID，以后用于给他推送消息。
    :param request: 
    :return: 
    """
    code = request.GET.get("code")

    # 用户md5值,用户唯一id
    state = request.GET.get("state")

    # 获取该用户openId(用户唯一，用于给用户发送消息)
    # request模块朝https://api.weixin.qq.com/sns/oauth2/access_token地址发get请求
    res = requests.get(
        url="https://api.weixin.qq.com/sns/oauth2/access_token",
        params={
            "appid": settings.WECHAT_CONFIG['app_id'],
            "secret": settings.WECHAT_CONFIG['appsecret'],
            "code": code,
            "grant_type": 'authorization_code',
        }
    ).json()
    # res.data   是json格式
    # res=json.loads(res.data)
    # res是一个字典
    # 获取的到openid表示用户授权成功
    openid = res.get("openid")
    if openid:
        models.UserInfo.objects.filter(uid=state).update(wx_id=openid)
        response = "<h1>授权成功 %s </h1>" % openid
    else:
        response = "<h1>用户扫码之后，手机上的提示</h1>"
    return HttpResponse(response)


def sendmsg(request):
    def get_access_token():
        """
        获取微信全局接口的凭证(默认有效期俩个小时)
        如果不每天请求次数过多, 通过设置缓存即可
        """
        result = requests.get(
            url="https://api.weixin.qq.com/cgi-bin/token",
            params={
                "grant_type": "client_credential",
                "appid": settings.WECHAT_CONFIG['app_id'],
                "secret": settings.WECHAT_CONFIG['appsecret'],
            }
        ).json()
        if result.get("access_token"):
            access_token = result.get('access_token')
        else:
            access_token = None
        return access_token
    access_token = get_access_token()
    openid = models.UserInfo.objects.get(id=1).wx_id

    def send_template_msg():
        """
        发送模版消息
        """
        res = requests.post(
            url="https://api.weixin.qq.com/cgi-bin/message/template/send",
            params={
                'access_token': access_token
            },
            json={
                "touser": openid,
                "template_id": settings.WECHAT_CONFIG['template_id'],
            }
        )
        result = res.json()
        return result
    ret = {'code': 1000}
    result = send_template_msg()
    if result.get('errcode') == 0:
        ret['msg'] = '发送成功'
        return JsonResponse(ret)
    return JsonResponse(ret)